$(function () {
    $("#jqGrid").jqGrid({
        url: baseURL + 'business/businessmessage/list',
        datatype: "json",
        colModel: [			
			{ label: 'id', name: 'id', index: 'id', width: 50, key: true, hidden:true },
			{ label: '短信类型', name: 'type', index: 'type', width: 80,align: 'center',
                formatter:function(value, options, row){
                    var valueText = "";
                    var messageTypeEnum = $("#jqGrid").jqGrid('getGridParam', 'userData').messageTypeEnum;
                    $.each(messageTypeEnum, function (index, module) {
                        if (module.id == value)
                            valueText = module.describe;
                    });
                    return valueText;
                }
			},
			{ label: '计划发送时间', name: 'sendTime', index: 'send_time', width: 80, align: 'center', },
			{ label: '发送条数', name: 'sendCount', index: 'send_count', width: 80,align: 'center', },
			{ label: '状态', name: 'status', index: 'status', width: 80,align: 'center',
                formatter:function(value, options, row){
                    //0未发送 1已发送
                return value==0?'未发送':'已发送'
                }
            },
            { label: '操作', name: 'option', index: 'option', width: 50 ,align: 'center', title:false,
                formatter:function(value, options, row){
                    var actions = [];
                        actions.push('<a href="javascript:void(0);" onclick="vm.check('+ row.id +');">查看</a>') ;
                    return actions.join('  ');
                }
            }
        ],
        caption:"营销统计",
        hidegrid:false,
		viewrecords: true,
        height: 385,
        rowNum: 10,
		rowList : [10,30,50],
        rownumbers: true, 
        rownumWidth: 25, 
        autowidth:true,
        multiselect: false,
        pager: "#jqGridPager",
        jsonReader : {
            root: "page.list",
            page: "page.currPage",
            total: "page.totalPage",
            records: "page.totalCount",
            userdata: "userData"
        },
        prmNames : {
            page:"page", 
            rows:"limit", 
            order: "order"
        },
        gridComplete:function(){
        	//隐藏grid底部滚动条
        	$("#jqGrid").closest(".ui-jqgrid-bdiv").css({ "overflow-x" : "hidden" });
            //取出人群和优惠券
            var userData = $("#jqGrid").jqGrid('getGridParam', 'userData');
            vm.peopleEntityList=userData.peopleEntityList;
            vm.messageTypeEnum=userData.messageTypeEnum;
        }
    });

    $("#jqGridPeople").jqGrid({
        url: baseURL + 'business/businessmessagepeople/list',
        datatype: "json",
        colModel: [
            { label: 'id', name: 'id', index: 'id', width: 50, key: true, hidden:true },
            { label: '人群名称', name: 'peopleName', index: 'people_name', width: 80, align: 'center' },
            { label: '人群定义', name: 'peopleDesc', index: 'people_desc', width: 80, align: 'center' },
            { label: '间隔时间(天)', name: 'gapDay', index: 'gap_day', width: 80, align: 'center' },
            { label: '操作', name: 'option', index: 'option', width: 50 ,align: 'center', title:false,
                formatter:function(value, options, row){
                    var actions = [];
                    actions.push('<a href="javascript:void(0);" onclick="vm.changeTime('+ options.rowId +');">修改时间</a>') ;
                    return actions.join('  ');
                }
            }
        ],
        caption:"人群管理",
        hidegrid:false,
        viewrecords: true,
        height: 185,
        rowNum: 10,
        rowList : [10,30,50],
        rownumbers: true,
        rownumWidth: 25,
        autowidth:true,
        multiselect: false,
        jsonReader : {
            root: "page.list",
            page: "page.currPage",
            total: "page.totalPage",
            records: "page.totalCount"
        },
        prmNames : {
            page:"page",
            rows:"limit",
            order: "order"
        },
        gridComplete:function(){
            //隐藏grid底部滚动条
            $("#jqGridPeople").closest(".ui-jqgrid-bdiv").css({ "overflow-x" : "hidden" });
        }
    });
    //下载Excel模板
    var $eleBtn2 = $("#btn2");
    $eleBtn2.click(function(){
        var $eleForm = $("<form method='get'></form>");
        $eleForm.attr("action","https://jdbc.oss-cn-beijing.aliyuncs.com/%E6%89%8B%E6%9C%BA%E5%8F%B7%E7%A0%81.xlsx");
        $(document.body).append($eleForm);
        //提交表单，实现下载
        $eleForm.submit();
    });
});



var vm = new Vue({
	el:'#rrapp',
	data:{
		showList: true,
        showInfo: false,
		title: null,
		businessMessage: {},
        peopleEntityList:[],
        messageTypeEnum:[]
	},
	methods: {
        checkBeginDate: function () {
            WdatePicker({dateFmt:'yyyy-MM-dd HH:mm:ss',isShowClear:false, onpicking:function (dp) {
                    vm.businessMessage.sendTime = dp.cal.getNewDateStr();
                }})
        },
		query: function () {
			vm.reload();
		},
		add: function(){
			vm.showList = false;
			vm.title = "新增";
			vm.businessMessage = {};
		},
        check: function (id) {
			if(id == null){
				return ;
			}
			vm.showList = false;
            vm.title = "查看营销统计";
            
            vm.getInfo(id)
		},
		saveOrUpdate: function (event) {
			var url = vm.businessMessage.id == null ? "business/businessmessage/save" : "business/businessmessage/update";
			$.ajax({
				type: "POST",
			    url: baseURL + url,
                contentType: "application/json",
			    data: JSON.stringify(vm.businessMessage),
			    success: function(r){
			    	if(r.code === 0){
						alert('操作成功', function(index){
							vm.reload();
						});
					}else{
						alert(r.msg);
					}
				}
			});
		},
		del: function (event) {
			var ids = getSelectedRows();
			if(ids == null){
				return ;
			}
			
			confirm('确定要删除选中的记录？', function(){
				$.ajax({
					type: "POST",
				    url: baseURL + "business/businessmessage/delete",
                    contentType: "application/json",
				    data: JSON.stringify(ids),
				    success: function(r){
						if(r.code == 0){
							alert('操作成功', function(index){
								$("#jqGrid").trigger("reloadGrid");
							});
						}else{
							alert(r.msg);
						}
					}
				});
			});
		},
		getInfo: function(id){
			$.get(baseURL + "business/businessmessage/info/"+id, function(r){
                vm.businessMessage = r.businessMessage;
            });
		},
		reload: function (event) {
			vm.showList = true;
			var page = $("#jqGrid").jqGrid('getGridParam','page');
			$("#jqGrid").jqGrid('setGridParam',{ 
                page:1
            }).trigger("reloadGrid");
		},
        businessMessageEdit:function () {
            vm.showInfo = true;
        },
        businessMessageCancel:function () {
            vm.showInfo = false;
        },
        //修改营销短信
        businessMessageUpdate: function (event) {
            $.ajax({
                type: "POST",
                url: baseURL + "business/businessmessage/update",
                dataType: "json",
                data: $("#updateForm").serialize(),
                success: function(r){
                    if(r.code === 0){
                        alert('操作成功', function(){
                            location.reload();
                        });
                    }else{
                        alert(r.msg);
                    }
                }
            });
        },
        //创建手机号码导入
        pushPhone: function() {
            layer.open({
                type: 1,
                skin: 'layui-layer-molv',
                title: "导入手机号码",
                area: ['750px', '480px'],
                shadeClose: false,
                content: jQuery("#pushPhone"),
                btn: ['确认发送','取消'],
                btn1: function (index) {
                    $.ajax({
                        type: "GET",
                        url: baseURL + "business/businessmessage/save",
                        dataType: "json",
                        data: $("#phoneForm").serialize(),
                        success: function(r){
                            if(r.code == 0){
                                layer.close(index);
                                alert('操作成功', function(){
                                    location.reload();
                                });
                            }else{
                                alert(r.msg);
                            }
                        }
                    });
                }
            });
        },
        //创建个性化营销
        personality: function() {
            layer.open({
                type: 1,
                skin: 'layui-layer-molv',
                title: "个性化营销",
                area: ['750px', '480px'],
                shadeClose: false,
                content: jQuery("#personality"),
                btn: ['确认发送','取消'],
                btn1: function (index) {
                    $.ajax({
                        type: "GET",
                        url: baseURL + "business/businessmessage/save",
                        dataType: "json",
                        data: $("#personalityForm").serialize(),
                        success: function(r){
                            if(r.code == 0){
                                layer.close(index);
                                alert('操作成功', function(){
                                    location.reload();
                                });
                            }else{
                                alert(r.msg);
                            }
                        }
                    });
                }
            });
        },
    //修改时间
    changeTime: function(rowId) {
        var rowData = $("#jqGridPeople").jqGrid('getRowData', rowId);
        $('#gapDay').val(rowData.gapDay);
        layer.open({
            type: 1,
            skin: 'layui-layer-molv',
            title: "修改时间",
            area: ['550px', '280px'],
            shadeClose: false,
            content: jQuery("#changeTime"),
            btn: ['保存','取消'],
            btn1: function (index) {
                var id = rowData.id;
                var time = $.trim($('#gapDay').val());
                if (isBlank(time)) {
                    alert("时间不能为空")
                    return false;
                }
                $.ajax({
                    type: "GET",
                    url: baseURL + "business/businessmessagepeople/update",
                    dataType: "json",
                    data: {
                        'id': id,
                        'gapDay': time,
                    },
                    success: function(r){
                        if(r.code == 0){
                            layer.close(index);
                            alert('操作成功', function(){
                                location.reload();
                            });
                        }else{
                            alert(r.msg);
                        }
                    }
                });
            }
        });
    },







	}
});
